package com.hangsu.train.components.service.impl;

import com.hangsu.train.components.convert.DeviceConvert;
import com.hangsu.train.components.dao.DeviceDao;
import com.hangsu.train.components.entity.Device;
import com.hangsu.train.components.params.DeviceParam;
import com.hangsu.train.components.params.DeviceUpdateParam;
import com.hangsu.train.components.params.IdParam;
import com.hangsu.train.components.params.PageRequestParam;
import com.hangsu.train.components.service.DeviceService;
import com.hangsu.train.heatbeat.Server;
import jakarta.annotation.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DeviceServiceImpl implements DeviceService {

    @Resource
    private DeviceDao deviceDao;
    @Resource
    private DeviceConvert deviceConvert;

    @Override
    public Device getById(IdParam param) {
        return deviceDao.selectByPrimaryKey(param.getId());
    }

    @Override
    public void add(DeviceParam param) {
        Device device=deviceConvert.convert(param);
        deviceDao.insert(device);
    }

    @Override
    public void update(Device device) {
        deviceDao.updateByPrimaryKey(device);
    }

    @Override
    public Page<Device> list(PageRequestParam param) {
        PageRequest request=PageRequest.of(param.getPage(), param.getPageSize());
        Device query=new Device();
        List<Device> list =  deviceDao.list(query,request.getOffset(),request.getPageSize());
        long count = deviceDao.count(query);
        return new PageImpl<>(list,request,count).map(item->{
            if(Server.getInstance().contains(item.getSerialNumber())){
                item.setIsOnline(1);
            }
            return item;
        });
    }

    @Override
    public void delete(IdParam param) {
        deviceDao.deleteByPrimaryKey(param.getId());
    }
}
